<?php

class Core_Model_Customer_Showroom_Certificate extends Dcmp_Model_Status {

    public function __construct() {
        parent::__construct();
    }
    
    public function getShowroom(){
    	return App::getModel('customer/showroom')->load($this->getShowroomId());
    }
    
    public function updateAccessTimes(){
        Kd_Data_Factory::getUpdateDcl()
                ->into($this->getTable()->getName())
                ->value('access_times', Kd_Data_Dcl_Fn::subtract('access_times', 1))
                ->where()->eq('id', ':id:i')->closest()
                ->addParameter('id', $this->getId())
                ->execute();
        return $this;
    }    
    
    public function updateClickCount(){
        Kd_Data_Factory::getUpdateDcl()
                ->into($this->getTable()->getName())
                ->value('click_count', Kd_Data_Dcl_Fn::addition('click_count', 1))
                ->where()->eq('id', ':id:i')->closest()
                ->addParameter('id', $this->getId())
                ->execute();
        return $this;
    }    
    
    public function loadByCode($showroomId, $code){
    	$row = Kd_Data_Factory::getQueryDcl()
	    		->from($this->getTable()->getName())
	    		->eq('showroom_id', ':showroomId:i')
	    		->eq('code', ':code:s')
	    		->addParameter(array('showroomId'=>$showroomId, 'code'=>$code))
	    		->limit(1)
	    		->fetch()
	    		->getFirstRow();
	    return $this->fill($row);
    }

    protected function initializeTable($table) {
        $table->setName('{t}customer_showroom_certificate');
        $table->createColumn('id', 'integer', TRUE, TRUE);
        $table->createColumn('showroom_id', 'integer');
        $table->createColumn('code', 'string')->setUpdateable(FALSE);
        $table->createColumn('access_times', 'integer');
        $table->createColumn('click_count', 'integer')->setDefaultValue(0);
        $table->createColumn('expiry_date', 'string');
        parent::initializeTable($table);
    }

}